package com.fingard.threading;

import java.util.concurrent.atomic.AtomicInteger;

/**同步器，当完成的计数到达预期值时，执行notifyAll
 * */
public class EventObject {
	
	/**同步对象mutex*/
	private Object mutexObj;
	
	/**完成计数*/
	private AtomicInteger setCount;
	
	/**预期完成数，当完成计数setCount的值达到expectCount时，结束等待*/
	private int expectCount;
	
	/**pExpectCount：设置预期完成数*/
	public EventObject(int pExptSetCount){
		mutexObj = new Object();
		setCount = new AtomicInteger();
		expectCount = pExptSetCount;
		setCount.set(0);
	}
	
	/**wait，当完成数未到预期值时，阻塞
	 * @param pTimeoutMil：等待最大毫秒数
	 * @throws InterruptedException */
	public boolean waitOne(long pTimeoutMil) throws InterruptedException {
		synchronized(mutexObj){
			mutexObj.wait(pTimeoutMil, 1000);
		}
		if(setCount.get() >= expectCount){
			return true;//正常结束
		}
		return false;
	}
	
	/**set完成数加1，如果到达预期值，则取消阻塞，执行notifyAll，并返回true*/
	public boolean setOne() throws InterruptedException{
		int cValue = setCount.incrementAndGet();
		if(cValue >= expectCount){
			synchronized(mutexObj){
				mutexObj.notifyAll();
			}
			return true;
		}
		return false;
	}
}
